var spiralOrder = function (matrix) {
  let ans = [];
  let i = 0;
  let j = 0;
  let m = matrix.length - 1;
  if (m < 0) return [];
  let n = matrix[0].length - 1;
  let turn = n==0 ? 'd' : 'r';
  let right = n;
  let down = m;
  let left = 0;
  let up = 0;

  for (let k = 0; k < (m + 1) * (n + 1); k++) {
    ans.push(matrix[i][j])    
    if (turn == 'r') {
      j++;
      if (j == right) {
        up++;
        turn =  'd';
      }
    } else if (turn == 'd') {
      i++;
      if (i == down) {
        right--;
        turn = 'l';
      }
    } else if (turn == 'l') {
      j--;
      if (j == left) {
        down--;
        turn = 'u'
      }
    } else if (turn == 'u') {
      i--;
      if (i == up) {
        left++;
        turn = 'r';
      }
    }
  }
  return ans;
}

